import os

from PIL import Image, ImageDraw, ImageFont


def drawMessageImage(font_path, bg_color, text_color, text, output_path):
    """
    绘制包含中文消息的图片
    
    参数:
    - font: PIL字体对象
    - bg_color: 背景颜色 (RGBA元组)
    - text_color: 文字颜色 (RGBA元组)
    - text: 要显示的中文消息
    - output_path: 输出图片路径
    """
    try:
        # 加载字体
        try:
            font = ImageFont.truetype(font_path, 40)  # 增大字体大小
        except Exception as e:
            print(f"无法加载字体: {e}")
            raise

        # 创建临时图像来测量文本大小
        temp_img = Image.new('RGBA', (1, 1), (255, 255, 255, 0))
        temp_draw = ImageDraw.Draw(temp_img)

        try:
            # 对于较新版本的PIL/Pillow
            text_bbox = temp_draw.textbbox((0, 0), text, font=font)
            text_width, text_height =  (text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1])
        except AttributeError:
            # 对于较旧版本的PIL/Pillow
            text_width, text_height = temp_draw.textsize(text, font=font)
        
        # 计算图片尺寸
        img_width = text_width + 60
        img_height = 64
            
        # 创建新图像
        img = Image.new('RGBA', (img_width, img_height), (255, 255, 255, 0))
        draw = ImageDraw.Draw(img)
        x1, y1, x2, y2 = (0, 0, img_width, img_height)
        
        # 绘制圆角矩形背景
        # 确保圆角半径不会导致绘制错误
        radius = min(10, (x2 - x1) // 2, (y2 - y1) // 2)
        radius = 0
        
        # 使用更精确的方法绘制圆角矩形
        # 左上角圆角
        draw.pieslice((x1, y1, x1 + radius*2, y1 + radius*2), 180, 270, fill=bg_color)
        # 右上角圆角
        draw.pieslice((x2 - radius*2, y1, x2, y1 + radius*2), 270, 0, fill=bg_color)
        # 左下角圆角
        draw.pieslice((x1, y2 - radius*2, x1 + radius*2, y2), 90, 180, fill=bg_color)
        # 右下角圆角
        draw.pieslice((x2 - radius*2, y2 - radius*2, x2, y2), 0, 90, fill=bg_color)
        
        # 填充矩形主体部分
        draw.rectangle((x1 + radius, y1, x2 - radius, y2), fill=bg_color)
        draw.rectangle((x1, y1 + radius, x2, y2 - radius), fill=bg_color)

        # 绘制虚线框
        try:
            padding = 4
            draw.rectangle((x1 + padding, y1 + padding, x2 - padding - padding + 3, y2 - padding - padding + 3), outline=text_color, width=2)
            for i in range(10, x2 + y2, 12):
                if i < y2:
                    start = (i, 0)  # 斜线的起点
                    end = (0, i)   # 斜线的终点
                elif i > x2:
                    start = (x2, i - x2)  # 斜线的起点
                    end = (i - y2, y2)   # 斜线的终点
                else:
                    start = (i, 0)  # 斜线的起点
                    end = (i - y2, y2)   # 斜线的终点
                draw.line([start, end], fill=bg_color, width=4)
        except Exception as e:
            print(f"绘制斜线时发生错误: {e}")
        
        # 计算文字位置（精确居中）
        try:
            # 使用textbbox来更精确地定位文字
            text_bbox = draw.textbbox((0, 0), text, font=font)
            text_x = (img_width - (text_bbox[2] - text_bbox[0])) // 2 - text_bbox[0]
            text_y = (img_height - (text_bbox[3] - text_bbox[1])) // 2 - text_bbox[1]
        except AttributeError:
            # 回退到旧方法
            text_x = (img_width - text_width) // 2
            text_y = (img_height - text_height) // 2
            
        # 绘制文字
        draw.text((text_x, text_y), text, font=font, fill=text_color)

        # 保存图片
        img.save(output_path, format='PNG')
        print(f"图片已保存至: {output_path}")
        return True
    except Exception as e:
        print(f"绘制图片时发生错误: {e}")
        return False


def drawMessageBoxImage(font_path, border_colors, title, icon, text, output_path):
    """
    绘制包含中文消息的图片
    
    参数:
    - font_path: 字体文件路径
    - border_colors: 边框颜色列表
    - title: 标题文本
    - icon: 图标文件路径
    - text: 要显示的中文消息
    - output_path: 输出图片路径
    """
    try:
        font = ImageFont.truetype(font_path, 24)
    
        # 创建临时图像来测量文本大小
        temp_img = Image.new('RGBA', (1, 1), (255, 255, 255, 0))
        temp_draw = ImageDraw.Draw(temp_img)
        
        try:
            # 对于较新版本的PIL/Pillow
            text_bbox = temp_draw.textbbox((0, 0), text, font=font)
            text_width, text_height = (text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1])
        except AttributeError:
            # 对于较旧版本的PIL/Pillow
            text_width, text_height = temp_draw.textsize(text, font=font)
        
        # 计算图片尺寸
        img_width = max(text_width + 120, 360)
        img_height = 220
            
        # 创建新图像
        img = Image.new('RGBA', (img_width, img_height), (255, 255, 255, 255))
        draw = ImageDraw.Draw(img)
        x1, y1, x2, y2 = (0, 0, img_width, img_height)

        # 绘制边框
        draw.rectangle((0, 0, x2, y2), fill=border_colors[0])
        border_colors.append('#ffffff')
        try:
            for i in range(8, x2 + y2, 12):
                a = i // 12 % len(border_colors)
                bg_color = border_colors[a]
                if i < y2:
                    start = (i, 0)  # 斜线的起点
                    end = (0, i)   # 斜线的终点
                elif i > x2:
                    start = (x2, i - x2)  # 斜线的起点
                    end = (i - y2, y2)   # 斜线的终点
                else:
                    start = (i, 0)  # 斜线的起点
                    end = (i - y2, y2)   # 斜线的终点
                draw.line([start, end], fill=bg_color, width=12)
        except Exception as e:
            print(f"绘制斜线时发生错误: {e}")

        draw.rectangle((6, 6, x2 - 6, y2 - 6), fill='#ffffff')

        # 绘制标题
        title_x = 30
        title_y = 30
        font = ImageFont.truetype(font_path, 32)
        draw.text((title_x, title_y), title, font=font, fill='#303133', stroke_width=0, stroke_fill='#606266')

        start_x = 32
        # 绘制图标
        try:
            icon_x = start_x
            icon_y = 92
            icon_img = Image.open(icon)
            # 调整图标大小 - 使用更高质量的缩放
            icon_width, icon_height = 36, 36  # 增大图标尺寸
            icon_img = icon_img.resize((icon_width, icon_height), Image.LANCZOS)  # LANCZOS是最高质量的缩放算法
            img.paste(icon_img, (icon_x, icon_y), icon_img if icon_img.mode == 'RGBA' else None)
            start_x += icon_width + 8
        except Exception as e:
            print(f"绘制图标时发生错误: {e}")
        
        # 绘制文本
        text_x = start_x
        text_y = 98
        font = ImageFont.truetype(font_path, 24)
        draw.text((text_x, text_y), text, font=font, fill='#606266', stroke_width=0, stroke_fill='#909399')
        
        # 保存图片
        img.save(output_path, format='PNG')
        return True
    except Exception as e:
        print(f"绘制图片时发生错误: {e}")
        return False

